package com.tang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @Author Tom
 * @ClassName CheckCode
 * @Date 2021/10/29 22:25
 */
@Controller
@RequestMapping("userSystem")
public class CheckCode {
    /**
     * 产生4位随机字符串作为验证码
     * @return
     */
    private String generateCheckCode(){
        String baseCode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        int size = baseCode.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i=1;i<=4;i++){
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在baseCode字符串中获取下标为index的字符
            char c = baseCode.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }
    @RequestMapping("/code")
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //在内存中创建一个长80，宽30的图片，默认黑色背景; 参数一：长; 参数二：宽; 参数三：颜色
        int width = 80;
        int height = 38;
        BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);

        //获取画笔,设置画笔颜色为灰色,填充图片
        Graphics gp = image.getGraphics();
        gp.setColor(Color.gray);
        gp.fillRect(0,0,width,height);


        //产生4个随机验证码，将验证码放入HttpSession中
        String checkCode_server = generateCheckCode();
        //将验证码放入HttpSession中
        request.getSession().setAttribute("checkCode_server",checkCode_server);

        //设置画笔颜色为黄色,设置字体的小大为24，向图片上写入验证码
        gp.setColor(Color.YELLOW);
        gp.setFont(new Font("黑体", Font.BOLD,24));
        gp.drawString(checkCode_server,15,25);

        //将内存中的图片输出到浏览器 参数一：图片对象;参数二：图片的格式，如PNG,JPG,GIF;参数三：图片输出到哪里去
        ImageIO.write(image,"PNG",response.getOutputStream());
    }
}
